//
//  DnPhotoViewPage.m
//  DnPhotoGallery	
//
//  Created by Ngoc on 12/12/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//


#import "DnPhotoViewPage.h"

@interface DnPhotoViewPage (Private)
-(void) selectedItemHandler:(id) sender;
- (void)createSubviews;
-(void) reloadData;
-(void) setUpWithDefaultValue;
-(void) fetchDataFromSource;
-(void) reassignSubViews;
@end

@implementation DnPhotoViewPage
@synthesize dataSource=_dataSource, scrollView=_scrollView, numberOfRows=_numberOfRows, numberOfColumns=_numberOfColumns, cellMargin, numberOfItems, userData=_userData, isNeedReloadData =_isNeedReloadData;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpWithDefaultValue];
        [self createSubviews];
    }
    return self;
}
-(id) init
{
    self = [super init];
    if (self) {
        [self setUpWithDefaultValue];
        [self createSubviews];
    }
    return self;
}
- (void)createSubviews
{
    cellMargin = 3;
    _numberOfRows = 4;
    _numberOfColumns = 3;
    
    self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 
    self.contentMode = UIViewContentModeRedraw;
    //self.backgroundColor = [UIColor clearColor];
    self.backgroundColor = [UIColor clearColor];
    _scrollView = [[[UIScrollView alloc] initWithFrame:self.bounds] autorelease];
    _scrollView.delegate = self;
    _scrollView.backgroundColor = [UIColor clearColor];
    _scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _scrollView.alwaysBounceHorizontal = NO;
    _scrollView.alwaysBounceVertical = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.pagingEnabled = NO;
    [self addSubview:_scrollView];
    _useItems = [[NSMutableArray alloc]init ];
    _isNeedReloadData = YES;
//    [self reloadData];
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    if (_isNeedReloadData) {
        [self reloadData];
        _isNeedReloadData = NO;
    }
}
-(void) deleteItemAtIndex:(NSInteger)index animation:(BOOL)animation
{
    UIView *view = (UIView*) [_useItems objectAtIndex:index];
    
    if (animation) {
        [UIView animateWithDuration:1
                         animations:^
         {
             view.alpha = 0.0;
         }
                         completion:^(BOOL finished)
         { 
             [view removeFromSuperview];
             [_useItems removeObjectAtIndex:index];
             [self setNeedsLayout];
         }];
    }
    else 
    {
        [view removeFromSuperview];
        [_useItems removeObjectAtIndex:index];
        [self setNeedsLayout];
    }
    
}
-(void) setUpWithDefaultValue
{
    self.userData = [[NSMutableDictionary alloc]init];
    
    
}
- (void)setDataSource:(id<DnPhotoViewPageDatasource>)aDataSource
{
    _dataSource = aDataSource;
    //[self reloadData];
}


- (void)setNumberOfColumns:(NSUInteger)value
{
    _numberOfColumns = value;
    //[self reloadData];
}


- (void)setNumberOfRows:(NSUInteger)value
{
    _numberOfRows = value;
   // [self reloadData];
}


- (void)setCellMargin:(NSUInteger)value
{
    _cellMargin = value;
    //[self reloadData];
}
- (void)reloadData
{
    [self fetchDataFromSource];
    [self setNeedsLayout];
    [self reassignSubViews];
}
-(void) reassignSubViews
{
    for (UIView *v in self.scrollView.subviews) {
        [v removeFromSuperview];
    }
    
    for (NSInteger i = 0; i < self.numberOfItems; i++) {
        DnPhotoViewCell *cell = (DnPhotoViewCell*)[_useItems objectAtIndex:i];
        [_scrollView addSubview:cell];
    }
}
-(void) fetchDataFromSource
{
    if (_useItems) {
        [_useItems removeAllObjects];
    }
    for (NSInteger i = 0; i < self.numberOfItems; i++) {
        DnPhotoViewCell *cell = [self.dataSource pageView:self itemAtIndex:i];
        [_useItems insertObject:cell atIndex:i];
    }
    
}
-(void) layoutSubviews
{
    if (_useItems && [_useItems count]>0 && self.dataSource && self.numberOfRows > 0 && self.numberOfColumns > 0) {
        NSInteger noOfCols = self.numberOfColumns;
        NSInteger noOfRows = self.numberOfRows;
        
        BOOL isLandscape = UIInterfaceOrientationIsLandscape([[UIDevice currentDevice] orientation]);
        if (isLandscape) {
            // In landscape mode switch rows and columns
            noOfCols = self.numberOfRows;
            noOfRows = self.numberOfColumns;
        }
        
        CGRect gridBounds = self.scrollView.bounds;
        NSInteger rows = self.numberOfItems/self.numberOfColumns;
        CGRect cellBounds = CGRectMake(0, 0, (gridBounds.size.width-kDnPhotoViewCellButtonSizeWidth) / (float)noOfCols, 
                                       ((gridBounds.size.height+kDnPhotoViewCellButtonSizeHeight/2) / (float)noOfRows)-self.cellMargin);
        
        
        if (self.numberOfItems %self.numberOfColumns!=0) {
            rows+=1;
        }
        CGSize contentSize = CGSizeMake(gridBounds.size.width, (rows *  cellBounds.size.height)+kDnPhotoViewCellButtonSizeHeight);
        [self.scrollView setContentSize:contentSize];
        for (NSInteger i = 0; i < self.numberOfItems; i++) {
            DnPhotoViewCell *cell = [_useItems objectAtIndex:i];
            NSInteger row  = (int)floor((float)i / (float)noOfCols);
            
            CGFloat originx, originy;
            originx = (i % noOfCols) * cellBounds.size.width+kDnPhotoViewCellButtonSizeWidth/2;
            originy = row * cellBounds.size.height+kDnPhotoViewCellButtonSizeHeight/2;
            CGPoint origin = CGPointMake(originx, originy);
            
            CGRect f = CGRectMake(origin.x, origin.y, cellBounds.size.width, cellBounds.size.height);
            cell.frame = CGRectInset(f, self.cellMargin, self.cellMargin);
            [cell.userData setObject:[[NSNumber alloc]initWithInteger:i] forKey:@"indexItem"];
        }
        [self setNeedsDisplay];
    }
    
}
- (NSUInteger)numberOfItems
{
    return [self.dataSource numberOfCellsInPage:self];
}
- (void)dealloc
{
    [_useItems release];
    [self.scrollView release];   
    [self.dataSource release];
    [super dealloc];
}
@end
